<template>
  <view>
    <view :style="{ height: windowHeight + 'px' }">
      <camera
        v-show="!takePhotoSuccess"
        mode="normal"
        device-position="front"
        flash="off"
        :style="{ height: cameraHeight + 'px' }"
      >
        <cover-view style="width: 100%; height: 100%">
          <cover-view class="photo-txt"
            >请保持正脸在取景框中根据屏幕指示完成识别</cover-view
          >
          <cover-image
            class="photo-logo"
            src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3c302c2725a4d4f689e1e78ad5f4faaae.png"
          ></cover-image>
          <cover-view class="photo-tip-wrap">
            <cover-view class="photo-tip">
              <cover-image
                class="photo-tip-img"
                src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3792a030fe2174f53aab6e35857f13385.png"
              ></cover-image>
              <cover-view class="photo-tip-desc">正对手机</cover-view>
            </cover-view>
            <cover-view class="photo-tip">
              <cover-image
                class="photo-tip-img"
                src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3ea1cb6cd2b66443fab14afd959b10a5f.png"
              ></cover-image>
              <cover-view class="photo-tip-desc">光线充足</cover-view>
            </cover-view>
            <cover-view class="photo-tip">
              <cover-image
                class="photo-tip-img"
                src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3792a030fe2174f53aab6e35857f13385.png"
              ></cover-image>
              <cover-view class="photo-tip-desc">脸无遮挡</cover-view>
            </cover-view>
          </cover-view>
        </cover-view>
      </camera>
      <view
        v-show="takePhotoSuccess"
        class="photo-img"
        :style="{
          height: cameraHeight + 'px',
          backgroundImage: `url(${imgSrc})`,
        }"
      >
        <view class="photo-txt">请保持正脸在取景框中根据屏幕指示完成识别</view>
        <view class="photo-logo-wrap">
          <image
            class="photo-logo"
            src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3c302c2725a4d4f689e1e78ad5f4faaae.png"
          ></image>
        </view>

        <view class="photo-tip-wrap">
          <view class="photo-tip">
            <image
              class="photo-tip-img"
              src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3792a030fe2174f53aab6e35857f13385.png"
            ></image>
            <view class="photo-tip-desc">正对手机</view>
          </view>
          <view class="photo-tip">
            <image
              class="photo-tip-img"
              src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3ea1cb6cd2b66443fab14afd959b10a5f.png"
            ></image>
            <view class="photo-tip-desc">光线充足</view>
          </view>
          <view class="photo-tip">
            <image
              class="photo-tip-img"
              src="https://pic4.58cdn.com.cn/nowater/lbgfe/image/n_v3792a030fe2174f53aab6e35857f13385.png"
            ></image>
            <view class="photo-tip-desc">脸无遮挡</view>
          </view>
        </view>
      </view>
      <view class="photo-btn-wrap">
        <view class="photo-back" v-show="takePhotoSuccess" @tap="handleCancel"
          >取消</view
        >
        <view class="photo-sub" v-show="!takePhotoSuccess" @tap="takePhoto">
          拍照
        </view>
        <view class="photo-sub" v-show="takePhotoSuccess" @tap="handleUpload">
          上传
        </view>
        <!--          <view @tap="chooseImage"> 相册 </view>-->
      </view>
    </view>
  </view>
</template>

<script>
import { request, requestData } from '@/utils/http.js'
export default {
  name: 'takePhoto',
  data() {
    return {
      carriedUserid: '',
      windowHeight: 0,
      cameraHeight: 0,
      cameraContext: null,
      takePhotoSuccess: false,
      imgSrc: '',
    }
  },
  onLoad(option) {
    if (option && option.id) {
      console.log(option.id)
      this.carriedUserid = option.id
    }
  },
  onShow() {
    if (uni.createCameraContext) {
      this.cameraContext = uni.createCameraContext()
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      uni.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
      })
    }
    const systemInfo = uni.getSystemInfoSync()
    this.windowHeight = systemInfo.windowHeight
    this.cameraHeight = systemInfo.windowHeight - 60
  },
  methods: {
    initData() {
      if (uni.createCameraContext) {
        this.cameraContext = uni.createCameraContext()
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        uni.showModal({
          title: '提示',
          content:
            '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        })
      }
      const systemInfo = uni.getSystemInfoSync()
      this.windowHeight = systemInfo.windowHeight
      this.cameraHeight = systemInfo.windowHeight - 60
    },
    takePhoto() {
      this.cameraContext.takePhoto({
        quality: 'normal',
        success: (res) => {
          uni.showToast({
            title: '拍照成功，请点击上传',
            icon: 'none',
            duration: 1200,
          })
          this.imgSrc = res.tempImagePath
          this.takePhotoSuccess = true
        },
        fail: (err) => {
          uni.showToast({
            title: '拍照失败，请检查系统是否授权',
            icon: 'none',
            duration: 1200,
          })
          this.imgSrc = ''
          this.takePhotoSuccess = false
          console.log('图片拍照失败', err)
        },
      })
    },
    handleCancel() {
      this.imgSrc = ''
      this.takePhotoSuccess = false
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
          filePath: url,
          encoding: 'base64',
          success: (data) => {
            let str = data.data
            resolve(str)
          },
          fail: (err) => {
            uni.showToast({
              title: JSON.stringify(err),
              icon: 'none',
            })
          },
        })
      })
    },
    // 上传图片
    async handleUpload() {
      let param = {}

      if (this.imgSrc) {
        try {
          let data = await this.uploadFilePromise(this.imgSrc)
          if (data) {
            if (this.carriedUserid) {
              param = {
                user_id: this.carriedUserid,
                image_base64: data,
                image_ext: 'jpg',
              }
            } else {
              param = {
                user_id: uni.getStorageSync('user_id'),
                image_base64: data,
                image_ext: 'jpg',
              }
            }
            request('/user/facephoto/base64image/upload', param)
              .then((res) => {
                if (+res?.code === 0) {
                  uni.showToast({
                    title: '上传成功！',
                    icon: 'none',
                  })
                  if (this.carriedUserid) { //携行用户
                    setTimeout(() => {
                      uni.navigateTo({
                        url: '/pagesC/carryUserList/carryUserList',
                      })
                    },2000)
                  } else {
                    setTimeout(() => {
                      uni.navigateTo(
                        {
                          url: '/pagesC/myInfo/myInfo',
                        },
                        2000
                      )
                    })
                  }
                } else {
                  uni.showToast({
                    title: res?.msg || '上传失败！',
                    icon: 'none',
                  })
                }
              })
              .catch((err) => {
                err &&
                  uni.showToast({
                    title: err,
                    icon: 'none',
                  })
              })
          }
        } catch (err) {}
      }
    },
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: (res) => {
          console.log('相册选取成功', res)
          console.log(res.tempFilePaths[0])
          //emit('getImgPath', res.tempFilePaths[0]);
        },
        fail: (err) => {
          console.log('相册选取失败', err)
        },
      })
    },
    close() {},
  },
}
</script>

<style lang="less">
.icon-w569-h828 {
  width: 569rpx;
  height: 828rpx;
}

.controls {
  position: relative;
}

.bottom {
  width: 100%;
  background-color: #000;

  .wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80px;
    padding: 0 73rpx;
  }
}

.w569-h828 {
  width: 569rpx;
  height: 828rpx;
}

.w131-h131 {
  width: 131rpx;
  height: 131rpx;
}

.font-36-fff {
  font-size: 36rpx;
  color: #fff;
}
.msg {
  width: 100%;
  height: 100%;
  font-size: 50rpx;
  text-align: center;
}
.photo-txt {
  width: 100%;
  height: 200rpx;
  line-height: 200rpx;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  color: #a5a5a5;
  background-color: #fff;
  font-size: 28rpx;
}
.photo-logo-wrap {
  width: 100%;
  height: 590rpx;
}
.photo-logo {
  width: 100%;
  height: 590rpx;
}
.photo-tip-wrap {
  width: 100%;
  height: calc(100% - 790rpx);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}
.photo-tip {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.photo-tip-img {
  width: 109rpx;
  height: 109rpx;
}
.photo-tip-desc {
  color: #333;
  font-size: 28rpx;
  margin-top: 20rpx;
}
.photo-btn-wrap {
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 20rpx;
  padding-bottom: 25rpx;
  box-sizing: border-box;
}
.photo-back {
  color: #d5ad57;
  margin-right: 40rpx;
}
.photo-sub {
  background-image: linear-gradient(to right, #ecd9b4, #d5ad57);
  display: flex;
  justify-content: center;
  align-items: center;
  width: 560rpx;
  height: 80rpx;
  color: #fff;
  font-weight: bold;
  border-radius: 20rpx;
}
.photo-img {
  width: 100%;
  background-position: 0 0;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
</style>
